package com.zenglx.assembly.increasingSequence.starter;

import com.zenglx.assembly.increasingSequence.api.SequenceGeneratorConstant;
import com.zenglx.assembly.increasingSequence.impl.dao.SequenceGeneratorDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import static com.zenglx.assembly.increasingSequence.api.SequenceGeneratorConstant.DEFAULT_OPTIMISTIC_LOCK;


@ConditionalOnProperty(name = SequenceGeneratorConstant.SEQUENCE_GENERATOR_TYPE
        ,  havingValue = SequenceGeneratorConstant.SEQUENCE_GENERATOR_TYPE_LOCK)
@Component
@Slf4j
public class OptimisticLockInitStartStep implements ApplicationRunner {

    @Value("${com.zenglx.assembly.sequenceGenerator.isAutoCreate:1}")
    private String isAutoCreateTable;

    @Value("${com.zenglx.assembly.sequenceGenerator.tableName:optimistic_lock_sequence}")
    private String tableName;


    @Autowired
    private SequenceGeneratorDao optimisticLockSequenceDao;

    @Override
    public void run(ApplicationArguments args) {
        log.info("基于乐观锁的sequence组件启动,初始化数据开始......");
        if("1".equals(isAutoCreateTable)) {
            log.info("基于乐观锁的sequence组件自动化创建序列表");
            optimisticLockSequenceDao.dropTable(tableName);
            optimisticLockSequenceDao.createTable(tableName);
            optimisticLockSequenceDao.insert(tableName,DEFAULT_OPTIMISTIC_LOCK,1);
        }
        log.info("基于乐观锁的sequence组件启动,初始化数据完成");
    }
}
